package com.zhihuishu.treenity.service.operation.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.able.dto.ClassDto;
import com.able.dto.StudentDto;
import com.able.dto.UserSigninDto;
import com.able.openapi.overseas.IOnlineSchoolForOverseasService;
import com.able.openapi.overseas.dto.TeachingTaskDto;
import com.able.openapi.overseas.dto.UserSigninInfoDto;
import com.zhihuishu.micro.course.openapi.course.MeetCourseOpenService;
import com.zhihuishu.micro.course.openapi.course.dto.MeetCourseOpenDto;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.log.LoggerTemplate;
import com.zhihuishu.treenity.consts.Constants;
import com.zhihuishu.treenity.dto.StuInfoDto;
import com.zhihuishu.treenity.service.operation.ScoredetailService;
import com.zhihuishu.treenity.util.CopyObjUtils;
import com.zhihuishu.user.openapi.common.UserQueryOpenService;
import com.zhihuishu.user.openapi.common.dto.UserOpenDto;
import com.zhihuishu.user.openapi.wrapper.ResultWrapper;


@Service("scoredetailService")
public class ScoredetailServiceImpl implements ScoredetailService {
	
	protected LoggerTemplate log = LoggerTemplate.getInstance(this.getClass());
	
	@Resource
	public IOnlineSchoolForOverseasService iOnlineSchoolForOverseasService;
	@Resource
	private MeetCourseOpenService meetCourseOpenService;
	@Resource
	private UserQueryOpenService userQueryOpenService;



	@Override
	public List<StuInfoDto> stuInfo(Long courseId, Integer recruitId, Integer taskId)
			throws NumberFormatException, RemoteException {
		List<StuInfoDto> stuInfos=new ArrayList<StuInfoDto>();
	    //获取班级信息
		List<ClassDto> ClassDtos=iOnlineSchoolForOverseasService.findClassListRecruitId(recruitId);
		List<Long> ids=new ArrayList<Long>();
	     //查询课程下招生信息
		List<StudentDto> studentDtos=iOnlineSchoolForOverseasService.findStudentDtoByRecruitId(recruitId);
		//查询课程下有过签到的学习信息
		List<UserSigninInfoDto> userSigninInfoDtos=	iOnlineSchoolForOverseasService.findByRecruitIdAndTaskId(recruitId,taskId);
		for (int i = 0; i < studentDtos.size(); i++) {
			StuInfoDto stuInfoDto=new StuInfoDto();
			stuInfoDto.setSignStatus(0);
			if(!CollectionUtils.isEmpty(userSigninInfoDtos)){
				//封装数据
			for (int j = 0; j < userSigninInfoDtos.size(); j++) {
				if(userSigninInfoDtos.get(j).getUserId().equals(studentDtos.get(i).getStudentId())){
					stuInfoDto.setUpstay(1);
					stuInfoDto.setSignStatus(userSigninInfoDtos.get(j).getSignStatus());
					stuInfoDto.setSceneScore(userSigninInfoDtos.get(j).getSceneScore());
					stuInfoDto.setRealName(userSigninInfoDtos.get(j).getRealName());
					stuInfoDto.setId(userSigninInfoDtos.get(j).getId());
				}
			}
			}
		if(!CollectionUtils.isEmpty(studentDtos)&&studentDtos.get(i).getClassId()!=null)
			stuInfoDto.setClassId(Long.parseLong(studentDtos.get(i).getClassId().toString()));
		    stuInfoDto.setRecruitId(Long.parseLong(recruitId.toString()));
			stuInfoDto.setCourseId(courseId);
			stuInfoDto.setTaskId(taskId);
			ids.add(studentDtos.get(i).getStudentId());
			stuInfoDto.setRealName(studentDtos.get(i).getRealName());
			stuInfoDto.setUserId(studentDtos.get(i).getStudentId());
			stuInfos.add(stuInfoDto);
		}
		
		//查询用户信息图像 avatar
		ResultWrapper<List<UserOpenDto>> list = userQueryOpenService.list(ids);
		if(list.getResult()!=null){
		
		for (UserOpenDto userOpenDto : list.getResult()) {
			for (StuInfoDto stuInfoDto : stuInfos) {
				if(stuInfoDto.getUserId().equals(userOpenDto.getUserId())){
					
					
					String avatar="";
					// 完善用户头像
		        	if(StringUtils.isBlank(userOpenDto.getAvatar())) {
		        		// 为空是，填充默认用户头像
		        		avatar=Constants.FTP_URL_SUFFIX_IMG + Constants.USER_AVATAR_IMG_PATH;
		        	} else if(!StringUtils.startsWithIgnoreCase(userOpenDto.getAvatar(), "http")) {
		        		// 非以http开头时，添加前缀
		        		avatar=Constants.FTP_URL_SUFFIX_IMG + userOpenDto.getAvatar();
		        	}else{
		        		avatar=userOpenDto.getAvatar();
		        	}
		        	//对用户头像进行进一步操作，获取最小的图片
		        	avatar = avatar.substring(0,avatar.lastIndexOf("."))+Constants.FTP_URL_POSTFIX_S3_IMG+avatar.substring(avatar.lastIndexOf("."));
		        	stuInfoDto.setImgurl(avatar);
				}
			}
		}
		
		}
		return stuInfos;
	}

	@Override
	public Map<Object, Object> findMeetCourseById(Integer id) throws NumberFormatException, RemoteException {
		//查询见面课信息
		TeachingTaskDto teachingTaskDto=iOnlineSchoolForOverseasService.findById(id);
		 RemoteResult<MeetCourseOpenDto> MeetCourseOpenDto=  meetCourseOpenService.getMeetCourse( Long.parseLong(teachingTaskDto.getMeetCourseId().toString()));
		Map<Object,Object> mapinfo=new HashMap<Object, Object>();
		mapinfo.put("teachingTaskDto", teachingTaskDto);
		mapinfo.put("checkScore", MeetCourseOpenDto.getResult().getCheckScore());
		mapinfo.put("siteScore", MeetCourseOpenDto.getResult().getSiteScore());
		mapinfo.put("teachRequire", MeetCourseOpenDto.getResult().getTeachRequire());
		return mapinfo;
	}

	@Override
	public RemoteResult<Object> upOrSaveStu( List<StuInfoDto> upStuInfos, String isUp) {
		RemoteResult<Object> result=new RemoteResult<Object>();
		 List<UserSigninDto> saveuserSigninDtos=new ArrayList<UserSigninDto>();
		 List<UserSigninDto> upuserSigninDtos=new ArrayList<UserSigninDto>();
		try {
			for (int i=0;i<upStuInfos.size();i++) {
				UserSigninDto userSigninDto=new UserSigninDto();
				//获取新增集合
				if(upStuInfos.get(i).getUpstay()==0){
					CopyObjUtils.copyObj(userSigninDto, upStuInfos.get(i));
					saveuserSigninDtos.add(userSigninDto);
				}else{
					//获取修改集合
					CopyObjUtils.copyObj(userSigninDto, upStuInfos.get(i));
					userSigninDto.setIsDeleted("0");//设置默认值 0代表未删除
					upuserSigninDtos.add(userSigninDto);
				}
			}
				//更新
				String ids="";
				for (int i=0;i<upuserSigninDtos.size();i++) {
					ids+=upuserSigninDtos.get(i).getId()+((i+1)==upuserSigninDtos.size()?"":",");
				}
				if(upuserSigninDtos.size()!=0){
					if(isUp!=null&&isUp.equals("1"))
					upuserSigninDtos.get(0).setSceneScore(null);
					Integer	 number  =  iOnlineSchoolForOverseasService.updateUserSignin(upuserSigninDtos.get(0), ids);
					 result.setResult(number);
				}
				//保存
				if(saveuserSigninDtos.size()!=0){
				boolean	bool= iOnlineSchoolForOverseasService.saveMulitStuSignin(saveuserSigninDtos);
				 result.setResult(bool);
				}
		} catch (Exception e) {
			result.setResult(null);
			result.setSuccess(false);
		}
		return result;
	}
}
